import com.sun.mail.util.MailSSLSocketFactory;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.security.GeneralSecurityException;
import java.util.Properties;
public class EmailSender
{
    public static void main(String[] args){
        final String host = args[0];
        final String from = args[1];
        final String to = args[2];
        final String subject = args[3];
        final String body = args[4];
        final String userName = args[5];
        final String passWord = args[6];
        final String fileName = args[7];
        try {
            sendEmail(host,from,to,subject,body,userName,passWord,fileName);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
            System.out.println("send failure!");
        }


    }
    public static void sendEmail(String host,String from,String to, String subject, String body,String userName,String passWord,String fileName) throws GeneralSecurityException {
        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host",host);
        properties.setProperty("mail.smtp.auth","true");
        MailSSLSocketFactory mailSSLSocketFactory = new MailSSLSocketFactory();
        mailSSLSocketFactory.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.socketFactory",mailSSLSocketFactory);
        properties.put("mail.smtp.ssl.enable",true);
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(userName,passWord);
            }
        });
        try{
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.addRecipient(MimeMessage.RecipientType.TO,new InternetAddress(to));
            message.setSubject(subject);
            BodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body);
            Multipart multipart = new MimeMultipart();
            DataSource dataSource =new FileDataSource(fileName);
            messageBodyPart.setDataHandler(new DataHandler(dataSource));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);
            Transport.send(message);
            System.out.println("send success!");
        } catch (AddressException e) {
            throw new RuntimeException(e);
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }

    }
}
